package com.christophpurrer.shg2;

import java.text.DecimalFormat;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.TextView;
import android.widget.Toast;

import com.christophpurrer.R;

/**
 * partially based on:
 * http://stackoverflow.com/questions/2317428/android-i-want-to-shake-it
 * 
 * @author Christoph Purrer
 * 
 */
public class ShakingGestures2Acitivity extends Activity {

	// properties
	private SensorManager sensorManager = null;
	private AccelerometerManager accelerometerManager = null;
	private DecimalFormat decimalFormat = new DecimalFormat("#.##");

	/**
	 * called when the activity is first created
	 **/
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shaking_gestures2);
		final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

		this.sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		this.accelerometerManager = new AccelerometerManager();
		this.sensorManager.registerListener(this.accelerometerManager,
				this.sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_UI);

		this.accelerometerManager
				.setOnShakeListener(new AccelerometerManager.AccelerometerListener() {
					public void onShake() {
						vibrator.vibrate(100);
						Toast.makeText(ShakingGestures2Acitivity.this,
								"Shake!", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onAccelerationChanged(float x, float y, float z) {
						((TextView) findViewById(R.id.shaking_gestures2TvX))
								.setText("x: " + decimalFormat.format(x));
						((TextView) findViewById(R.id.shaking_gestures2TvY))
								.setText("y: " + decimalFormat.format(y));
						((TextView) findViewById(R.id.shaking_gestures2TvZ))
								.setText("z: " + decimalFormat.format(z));
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		// register the sensorListener
		this.sensorManager.registerListener(accelerometerManager,
				this.sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_UI);
	}

	@Override
	protected void onStop() {
		// unregister the sensorListener to save battery power
		this.sensorManager.unregisterListener(accelerometerManager);
		super.onStop();
	}
}
